Dict = require('../models/dict').Dict
dataPage = require('../services/dataPage').queryPage
resErr = require('./util').resErr
util = require("util")
common_util = require('../services/common_util')
async = require('async')
SysUser = require('../models/sys_user').SysUser

exports.dict_add = (req,res) ->
  key_code = common_util.trim(req.param("key_code"))
  key_name = common_util.trim(req.param("key_name"))
  if !key_code
    res.json({'flag':'error','msg':'字典编码不能为空！'})
  else if !key_name
    res.json({'flag':'error','msg':'字典显示名不能为空！'})
  else
    Dict.count {"key_code":key_code},(err,count) ->
      if err
        res.json({'flag':'error','msg':err})
      else
        if count > 0
          res.json({'flag':'error','msg':'字典编码已存在！'})
        else
          dict = new Dict
          dict.add req,(err)->
            if err
              resErr(res,err)
            else
              res.json({'flag':'success'})





exports.dict_list = (req,res) ->
  params = {}
  #相当于sql里面like的写法
  params.parent_code = req.param("parent_code") unless !req.param("parent_code")
  params.key_code = req.param("key_code") unless !req.param("key_code")
  params.key_name = req.param("key_name") unless !req.param("key_name")
  sorts = {}
  sorts.key_code = 1
  Dict.find(params).sort(sorts).exec (err,dict) ->
    if err
      resErr res,err
    else
      console.log params
      console.log dict
      res.json dict

exports.dict_list_simple = (req,res) ->
  Dict.find (err,dicts) ->
    result = {}
    for d in dicts
      result[d.key_code] = d.key_name if d.key_code
    return res.json result

exports.dict_tree = (req,res) ->
  Dict.find {},(err,dicts) ->
    if err
      resErr(res,err)
    else
      tree_data = []
      tree_data.push {id:'root', pId:'', name:"字典根节点", open:true,url:"list.html?parent_code=root",target:"rightFrame"}
      for d in dicts
        tree_data.push {id:d.key_code,pId:d.parent_code,name:d.key_name,url:'list.html?parent_code='+d.key_code,target:"rightFrame"}
      res.json(tree_data)

exports.dict_del = (req,res) ->
  if !req.param('_id')
    resErr(res,'编码不得为空')
  else
    _id = req.param('_id')
    Dict.findById _id,(err,dict) ->
      if err
        resErr(res,err)
      else
        key_code = dict.key_code
        Dict.count {"parent_code":key_code},(err,count) ->
          if err
            resErr(res,err)
          else
            if count > 0
              res.json({'flag':'error','msg':'该字典下有子字典，不能删除！'})
            else
              Dict.findByIdAndRemove _id,(err)->
                if err
                  resErr res,err
                else
                  res.json({'flag':'success'})



exports.dict_detail = (req,res) ->
  _id = req.param("_id")
  if !_id
    res.json({'success':false,'err_msg':'编码不得为空！'})
  else
    Dict.findById _id,(err,result) ->
      if err
        resErr(res,err)
      else
        res.json(result)


exports.dict_edit = (req,res) ->
  _id = req.param('_id')
  if !_id
    return resErr(res,'编码不得为空')

  key_code = common_util.trim(req.param("key_code"))
  key_name = common_util.trim(req.param("key_name"))
  if !key_code
    res.json({'flag':'error','msg':'字典编码不能为空！'})
  else if !key_name
    res.json({'flag':'error','msg':'字典显示名不能为空！'})
  else
    Dict.count {"_id":{"$ne":_id},"key_code":key_code},(err,count) ->
      if err
        resErr res,err
      else
        if count > 0
          res.json({'flag':'error','msg':'字典编码已存在！'})
        else
          Dict.findById _id,(err,dict) ->
            if err
              resErr res,err
            else
              Dict.update {"parent_code":dict.key_code},{"parent_code":key_code},{ multi: true },(err) ->
                if err
                  resErr res,err
                else
                  params = {}
                  params.key_desc = req.param('key_desc')
                  params.key_code = req.param('key_code')
                  params.key_name = req.param('key_name')
                  Dict.findByIdAndUpdate _id,params,(err) ->
                    if err
                      resErr(res,err)
                    else
                      res.json({'flag':'success'})

#获取Ext下拉树结构：
#1.根据栏目权限返回不需要复选框的树
#2.返回所有栏目带复选框的树（根据传入用户名判断拥有哪些栏目权限并默认选中）
exports.dicts_tree_ext = (req, res) ->
  console.log 'request dict trees ...'
  parent_code = req.param('parent_code') || 'root'
  checkbox = req.param('checkbox') || false
  #获取用户栏目权限数组
  user = req.session.admin_user
  username = req.param('username') || user.username
  categorys = null
  async.waterfall [
    (cb) ->
      #console.log '查询用户信息...'
      if username
        params = {}
        sorts = {}
        sorts.username = 1
        params.username = username
        SysUser.findOne(params).sort(sorts).exec (err, users) ->
          #console.log '进入查询....'
          return cb err if err
          #console.log 'length:'+users.length
          categorys = users.categorys
          return cb null
      else
        return cb null
    (cb) ->
      params = {}
      sorts = {}
      params.parent_code = parent_code
      sorts.sorder = 1
      Dict.find(params).sort(sorts).exec (err,dicts) ->
        if err
          return cb err
        else
          objs = null
          getDictTreeStr dicts,checkbox,categorys,(error,result) ->
            #console.log 'getDictTreeStr调用成功！'
            if error
              return cb error
            res.json result
  ],(error) ->
    return resErr res, error if error

getDictTreeStr = (datas, checkbox, categorys, callback_) ->
  #console.log 'getDictTreeStr...'
  return null if !datas or datas.length < 1
  results = new Array()
  async.eachSeries datas,(data,callback) ->
    childs = new Array()
    child = {}
    async.waterfall [
      (cb) ->
        #获取子节点
        params = {}
        sorts = {}
        params.parent_code = data.key_code
        sorts.sorder = 1
        Dict.find(params).sort(sorts).exec (err,dicts) ->
          if err
            return cb err
          else
            #console.log dicts
            childs = dicts
            return cb null
      (cb) ->
        if childs.length > 0
          child.id = data.key_code
          child.text = data.key_name
          child.leaf = false
          if checkbox
            child.checked = ischecked data.key_code,categorys
          else
            #不需要复选框的请求 都需要根据栏目权限过滤
            flag = ischecked data.key_code,categorys
            if !flag
              return cb null
          getDictTreeStr childs,checkbox,categorys,(e, o) ->
            if e
              return cb e
            child.children = o
            results.push child
            return cb null
        else
          child.id = data.key_code
          child.text = data.key_name
          child.leaf = true
          if checkbox
            child.checked = ischecked data.key_code,categorys
          else 
            #不需要复选框的请求 都需要根据栏目权限过滤
            flag = ischecked data.key_code,categorys
            if !flag
              return cb null
          child.tag = "abcd1234"
          results.push child
        #console.log results
          return cb null
    ],(error) ->
      #console.log '循环结束'
      if error
        #console.log '出错了...'
        #console.log error
        callback error
      else
        callback null
  ,(error) ->
    #console.log '循环出错了...' if error
    #console.log '+++++++++++++++++++'
    #console.log results
    #console.log '循环全部结束！！！'
    callback_ error,results

ischecked = (key_code, categorys) -> 
  if(categorys && categorys.length > 0)
    flag = false
    for category in categorys
      if key_code == category
        flag = true
        break
    return flag
  else
    return false